
package XMLPack;
import Data.*;
import Graphic.AccesLevel;
import Graphic.MainForm;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

// using SAX
public class SaxParser implements FileParserI
{

    private String answer = null;
    private boolean isAnswer = false;
    MainForm form = null;
    private Car car = null;
    private User user = null;
    private Ticket ticket = null;
    private Employee employee = null;

    private String fileName = null;
    boolean theEnd = false;
    public SaxParser(MainForm form)
    {
       this.form = form;

    }

    class ClientHandler extends DefaultHandler
    {

        boolean _answer = false;
        boolean _error = false;
        boolean _result = false;

        boolean _check_user = false;
        //boolean _isValidUser = false;

        boolean _insert_employee = false;
        boolean _delete_reservation = false;
        boolean _delete_car = false;

        boolean _make_reservation = false;
        boolean _edit_route = false;

        boolean _all_cars = false;
        boolean _car = false;
        boolean _carId = false;
        boolean _carNumber = false;
        boolean _carModel = false;
        boolean _seatsNumber = false;
        boolean _kmNumber = false;
        boolean _maintenanceCost = false;
        boolean _fuelConsumption = false;

        boolean _route_report = false;
        boolean _firstName = false;
        boolean _lastName = false;
        boolean _destination = false;
        boolean _departure = false;
        boolean _price = false;
        boolean _date = false;
        boolean _ticketSeries = false;

        boolean _month_report = false;
        boolean _ticket = false;

        boolean _select_car = false;
        boolean _edit_car = false;
        boolean _insert_car = false;

        boolean _cities_list = false;
        boolean _city = false;
        boolean _get_km = false;
        boolean _km = false;
       // boolean _route = false;

        boolean _totalCost = false;
        boolean _all_users = false;
        boolean _user = false;

        boolean _employeeSalary = false;
        boolean _employee = false;
        boolean _earning = false;
        boolean _workHours = false;
        boolean _bonus = false;

        boolean _city_a = false;
        boolean _city_d = false;
       boolean _deleteEmployee = false;

       @Override
        public void startElement(String nsURI,
                                 String strippedName,
                                 String tagName,
                                 Attributes attributes)  throws SAXException
        {

            if (tagName.equalsIgnoreCase("check_user"))
                _check_user = true;
           // if (tagName.equalsIgnoreCase("isValidUser"))
             //   _isValidUser = true;

            if (tagName.equalsIgnoreCase("insert_employee"))
                _insert_employee = true;

            if (tagName.equalsIgnoreCase("delete_reservation"))
                _insert_employee = true;

             if (tagName.equalsIgnoreCase("make_reservation"))
                _insert_employee = true;
             if (tagName.equalsIgnoreCase("delete_car"))
                _delete_car = true;

             if (tagName.equalsIgnoreCase("edit_route"))
                _edit_route = true;

            if (tagName.equalsIgnoreCase("result"))
                _result = true;
            if (tagName.equalsIgnoreCase("error"))
               _error = true;
            if (tagName.equalsIgnoreCase("answer"))
                _answer = true;

             // all cars
            if (tagName.equalsIgnoreCase("car"))
                 _car = true;
             if (tagName.equalsIgnoreCase("all_cars"))
                _all_cars = true;
            if (tagName.equalsIgnoreCase("carId"))
                _carId = true;
            if (tagName.equalsIgnoreCase("carNumber"))
                _carNumber = true;
            if (tagName.equalsIgnoreCase("carModel"))
               _carModel = true;
            if (tagName.equalsIgnoreCase("seatsNumber"))
                _seatsNumber = true;
            if (tagName.equalsIgnoreCase("kmNumber"))
               _kmNumber = true;
            if (tagName.equalsIgnoreCase("maintenanceCost"))
                _maintenanceCost = true;
            if (tagName.equalsIgnoreCase("fuelConsumption"))
               _fuelConsumption = true;

                if (tagName.equalsIgnoreCase("select_car"))
               _select_car = true;
            if (tagName.equalsIgnoreCase("edit_car"))
               _edit_car = true;
              if (tagName.equalsIgnoreCase("insert_car"))
               _insert_car = true;

            //route report
             if (tagName.equalsIgnoreCase("ticket"))
                 _ticket = true;
            if (tagName.equalsIgnoreCase("route_report"))
                 _route_report = true;
            if (tagName.equalsIgnoreCase("firstName"))
                 _firstName = true;
            if (tagName.equalsIgnoreCase("lastName"))
                 _lastName = true;
            if (tagName.equalsIgnoreCase("destination"))
                 _destination = true;
            if (tagName.equalsIgnoreCase("departure"))
                 _departure = true;
            if (tagName.equalsIgnoreCase("ticketSeries"))
                 _ticketSeries = true;
            if (tagName.equalsIgnoreCase("date"))
                 _date = true;
            if (tagName.equalsIgnoreCase("price"))
                 _price = true;

            //month report
             if (tagName.equalsIgnoreCase("month_report"))
                 _month_report = true;
             if (tagName.equalsIgnoreCase("ticket"))
                 _ticket = true;
            // cities list
             if (tagName.equalsIgnoreCase("cities_list"))
                 _cities_list = true;
             if (tagName.equalsIgnoreCase("city"))
                 _city = true;
             if (tagName.equalsIgnoreCase("city_a"))
                 _city_a = true;
             if (tagName.equalsIgnoreCase("city_d"))
                 _city_d = true;
             if (tagName.equalsIgnoreCase("get_km"))
                 _get_km = true;
             if (tagName.equalsIgnoreCase("km"))
                 _km = true;
            //total cost
            if (tagName.equalsIgnoreCase("total_cost"))
                 _totalCost = true;

            //employee salary
             if (tagName.equalsIgnoreCase("employee_salary"))
                 _employeeSalary = true;
             if (tagName.equalsIgnoreCase("employee"))
                 _employee = true; 
             if (tagName.equalsIgnoreCase("earning"))
                 _earning = true;
             if (tagName.equalsIgnoreCase("workHours"))
                 _workHours = true;
             if (tagName.equalsIgnoreCase("bonus"))
                 _bonus = true;

               if (tagName.equalsIgnoreCase("all_users"))
                 _all_users = true;
             if (tagName.equalsIgnoreCase("user"))
                 _user = true;

             if (tagName.equalsIgnoreCase("delete_employee"))
                 _deleteEmployee = true;


        }

        @Override
        public void characters(char[] ch, int start, int length)
        {

          //if(_answer)
          //{
              if(_check_user && _result)
              {
                String str = new String(ch,start,length);

                System.out.println("saxparser: "+str);
                _result = false;
                JOptionPane.showMessageDialog(form,
                                "Current user is "+str, "User",
                                JOptionPane.PLAIN_MESSAGE);



               AccesLevel level =  AccesLevel.getInstance();
               level.setName(form.getLoginDialog().getUser());
               System.out.println(form.getLoginDialog().getUser()+"111"+
                        form.getAccesLevel().getName());
            if (str.equalsIgnoreCase("dmanager"))
            {

                level.setDataManager(true);
                System.out.println("dataManager" + str);
                form.getLoginDialog().setVisible(false);

            } else if (str.equalsIgnoreCase("accountant"))
            {
                level.setAccountant(true);
                System.out.println("Accountant" + str);
                form.getLoginDialog().setVisible(false);

            }
            else  if (str.equalsIgnoreCase("none"))
            {
                level.setNone(true);
                System.out.println("Check user and password!!");
                form.getLoginDialog().setVisible(true);
            }
                else  if (str.equalsIgnoreCase("secretary"))
            {
                    form.getLoginDialog().setVisible(false);
                    level.setSecretary(true);
            }
                 form.setAccesLevel(level);



              }

              else if(_insert_employee && _result)
              {
                  String str = new String(ch,start,length);
                  JOptionPane.showMessageDialog(form,
                                str, "Insert employee",
                                JOptionPane.PLAIN_MESSAGE);
                  System.out.println("saxparser: "+str);
                  _result = false;
              }
            else if(_delete_reservation && _result){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Delete Reservation",
                                JOptionPane.PLAIN_MESSAGE);
                  System.out.println("saxparser delete reservation: "+str);
                  _result = false;
            }
               else if(_delete_reservation && _error){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Delete Reservation",
                                JOptionPane.ERROR_MESSAGE);
                  System.out.println("saxparser delete reservation error: "+str);
                  _error = false;
            }

            else if(_make_reservation && _result){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Make Reservation",
                                JOptionPane.PLAIN_MESSAGE);
                  System.out.println("saxparser make reservation: "+str);
                  _result = false;
            }
               else if(_make_reservation && _error){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Make Reservation",
                                JOptionPane.ERROR_MESSAGE);
                  System.out.println("saxparser make reservation error: "+str);
                  _error = false;
            }

              //edit route
              else if(_edit_route && _result){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Edit Route",
                                JOptionPane.PLAIN_MESSAGE);
                  System.out.println("saxparser edit route: "+str);
                  _result = false;
            }
               else if(_edit_route && _error){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Edit route",
                                JOptionPane.ERROR_MESSAGE);
                  System.out.println("saxparser edit route error: "+str);
                  _error = false;
            }

             // all cars
              else if((_all_cars || _select_car) && _car)
              {
                 car = new Car();
                 _car = false;
                  System.out.println("new car ******");
              }
              else if((_all_cars || _select_car) && _carId )
              {
                car.setCarId(Integer.parseInt(new String(ch, start,length)));
                _carId = false;
                System.out.println("id "+Integer.parseInt(new String(ch, start,length)));
              }
              else if((_all_cars || _select_car) && _carNumber )
              {
                car.setNumber(new String(ch, start,length));
                _carNumber = false;
                 System.out.println("carnumber "+(new String(ch, start,length)));
              }
              else if((_all_cars || _select_car) && _carModel )
              {
                car.setModel(new String(ch, start,length));
                _carModel = false;
                 System.out.println("model "+(new String(ch, start,length)));
              }
               else if((_all_cars || _select_car) && _kmNumber )
              {
                car.setKmNumber(Integer.parseInt(new String(ch, start,length)));
                _kmNumber = false;
                 System.out.println("km "+Integer.parseInt(new String(ch, start,length)));
              }
              else if((_all_cars || _select_car) && _seatsNumber )
              {
                car.setSeatsNumber(Integer.parseInt(new String(ch, start,length)));
                _seatsNumber = false;
              }
               else if((_all_cars || _select_car) && _fuelConsumption )
              {
                car.setFuelConsumption(Double.parseDouble(new String(ch, start,length)));
                _fuelConsumption = false;
                 System.out.println("fuel "+Integer.parseInt(new String(ch, start,length)));
              }
              else if((_all_cars || _select_car) && _maintenanceCost )
              {
                car.setMaintenanceCost(Double.parseDouble(new String(ch, start,length)));
                _maintenanceCost = false;
                 System.out.println("maint "+Integer.parseInt(new String(ch, start,length)));
              }
              //route report

              else if(_route_report && _lastName && _ticket){

                  user.setLastName(new String(ch, start, length));
                  _lastName=false;
              }
              else if(_route_report && _firstName && _ticket){
                   user = new User();
                  user.setFirstName(new String(ch, start, length));
                  _firstName=false;
              }
              else if(_route_report && _departure && _ticket){
                  ticket = new Ticket();
                  ticket.setDeparture(new String(ch,start,length));
                  _departure=false;
              }
               else if(_route_report && _destination && _ticket){

                  ticket.setDestination(new String(ch,start,length));
                  _destination=false;
              }
               else if(_route_report && _ticketSeries && _ticket){

                  ticket.setTicketSeries(Integer.parseInt(new String(ch,start,length)));
                  _ticketSeries=false;
              }
               else if(_route_report && _date && _ticket){

                  ticket.setDepartureDate(new String(ch,start,length));
                  _date=false;
              }
               else if(_route_report && _price && _ticket){

                  ticket.setPrice(Integer.parseInt(new String(ch,start,length)));
                  _price=false;
              }

              else if(_route_report && _error){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Route Report",
                                JOptionPane.ERROR_MESSAGE);
                  System.out.println("saxparser route report error: "+str);
                  _error = false;
            }

              //month report
              /* else if(_month_report && _ticket){
                  user = new User();
                  ticket = new Ticket();

              }*/
             else if(_month_report && _lastName){
                 user.setLastName(new String(ch, start, length));
                 _lastName=false;
             }
              else if(_month_report && _firstName){
                  user = new User();
                  ticket = new Ticket();
                  user.setFirstName(new String(ch, start, length));
                  _firstName=false;
              }
              else if(_month_report && _departure){
                  ticket.setDeparture(new String(ch,start,length));
                  _departure=false;
              }
               else if(_month_report && _destination){

                  ticket.setDestination(new String(ch,start,length));
                  _destination=false;
              }
               else if(_month_report && _ticketSeries){

                  ticket.setTicketSeries(Integer.parseInt(new String(ch,start,length)));
                  _ticketSeries=false;
              }
               else if(_month_report && _date){

                  ticket.setDepartureDate(new String(ch,start,length));
                  _date=false;
              }
               else if(_month_report && _price){

                  ticket.setPrice(Integer.parseInt(new String(ch,start,length)));
                  _price=false;
              }
              else if(_month_report && _error){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Route Report",
                                JOptionPane.ERROR_MESSAGE);
                  System.out.println("saxparser route report error: "+str);
                  _error = false;
            }



              //delete car
               else if(_delete_car && _result){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Delete car",
                                JOptionPane.PLAIN_MESSAGE);
                  System.out.println("saxparser delete car: "+str);
                  _result = false;
            }
               else if(_delete_car && _error){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Delete Car",
                                JOptionPane.ERROR_MESSAGE);
                  System.out.println("saxparser delete car error: "+str);
                  _error = false;
            }
               else if(_result){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Message",
                                JOptionPane.PLAIN_MESSAGE);
                  System.out.println("saxparser result: "+str);
                  _result = false;
            }

             else if(_error){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Error",
                                JOptionPane.ERROR_MESSAGE);
                System.out.println("saxparser error: "+str);
                _error = false;
            }
            else if (_cities_list && _city_d)
            {
                
                form.getReservation().departureCombo.addItem(new String(ch,start,length));
                _city_d = false;
                System.out.println("city"+new String(ch,start,length));

            }
               else if (_cities_list && _city_a)
            {
                form.getReservation().arrivalCombo.addItem(new String(ch,start,length));
                _city_a = false;
                System.out.println("city"+new String(ch,start,length));

            }
            else if(_get_km && _km)
            {
                form.getReservation().setKm(Integer.parseInt(new String(ch,start,length)));
                _km = false;
            }

              else if(_totalCost && _car)
            {
                  car = new Car();
                  _car = false;
             }
              else if(_totalCost && _carNumber){
                  car.setNumber(new String(ch,start,length));
                  _carNumber= false;
              }
               else if(_totalCost && _maintenanceCost){
                  car.setMaintenanceCost(Double.parseDouble(new String(ch,start,length)));
                  _maintenanceCost = false;
              }
              else if(_totalCost && _carModel){
                  car.setModel(new String(ch,start,length));
                  _carModel = false;
              }
                // else if(_employeeSalary && _employee){
                    
                   
                // }
                else if(_employeeSalary && _firstName && _employee){
                    employee = new Employee();
                    employee.setFirstName(new String(ch,start,length));
                    _firstName = false;
                   
                 }
                else if(_employeeSalary && _lastName && _employee){
                    employee.setLastName(new String(ch,start,length));
                    _lastName=false;

                 }
              else if(_employeeSalary && _earning && _employee){
                    employee.setEarning(Integer.parseInt(new String(ch,start,length)));
                    _earning=false;
                 }
             else if(_employeeSalary && _workHours && _employee){
                    employee.setWorkHours(Integer.parseInt(new String(ch,start,length)));
                    _workHours=false;
                 }
             else if(_employeeSalary && _bonus && _employee){
                    employee.setBonus(Integer.parseInt(new String(ch,start,length)));
                    _bonus=false;
                   
                 }

                //all users
                else if(_all_users && _lastName && _user){

                  user.setLastName(new String(ch, start, length));
                  _lastName=false;
              }
              else if(_all_users && _firstName && _user){
                   user = new User();
                  user.setFirstName(new String(ch, start, length));
                  _firstName=false;
              }
              else if(_all_users && _kmNumber && _user)
              {
                 _kmNumber = false;
                   user.setKmNumber(Integer.parseInt(new String(ch, start, length)));
              }

               else if(_deleteEmployee && _result){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Delete Employee",
                                JOptionPane.PLAIN_MESSAGE);
                  System.out.println("saxparser delete Employee: "+str);
                  _result = false;
            }
               else if(_deleteEmployee && _error){
                String str = new String(ch,start,length);
                JOptionPane.showMessageDialog(form,
                                str, "Delete Employee",
                                JOptionPane.ERROR_MESSAGE);
                  System.out.println("saxparser delete employee error: "+str);
                  _error = false;
            }
       }

 @Override
        public void endElement(String uri, String localName, String tag) throws SAXException
         {
            super.endElement(uri, localName, tag);
             if (tag.equalsIgnoreCase("car")&& _all_cars)
           {
              DefaultTableModel m = form.getEditCarPanel().getTableModel();

              Object [] data = {car.getNumber(), car.getModel(), car.getSeatsNumber(),
                         car.getKmNumber(), car.getMaintenanceCost(),
                         car.getFuelConsumption()};
              if(car != null)
                m.addRow(data);
               _car = false;
               car = null;
             }
            if (tag.equalsIgnoreCase("ticket")&& _route_report )
           {
              DefaultTableModel m = form.getRouteReportAnswer().getTableModel();
            
              Object [] data = {user.getFirstName(), user.getLastName(),
                        ticket.getDeparture(), ticket.getDestination(),
                        ticket.getTicketSeries(), ticket.getDepartureDate(),
                        ticket.getPrice()};
              if(user != null)
                m.addRow(data);
               _ticket = false;
               user = null;
               ticket = null;
             }
             if (tag.equalsIgnoreCase("ticket")&& _month_report)
           {
              DefaultTableModel m = form.getRouteReportAnswer().getTableModel();
              if(user != null && ticket != null){
              Object [] data = {user.getFirstName(), user.getLastName(),
                        ticket.getDeparture(), ticket.getDestination(),
                        ticket.getTicketSeries(), ticket.getDepartureDate(),
                        ticket.getPrice()};

                m.addRow(data);
               }
               _ticket = false;
               user = null;
               ticket = null;
             }


            if (tag.equalsIgnoreCase("car") && _select_car)
            {
                form.getNewCar().setCar(car);
            }
            if (tag.equalsIgnoreCase("ticket")){
                _ticket=false;
            }
             if(tag.equalsIgnoreCase("user") && _all_users)
            {
                _user = false;
                DefaultTableModel m = form.getCustomer().getModel();
            
             Object [] data = {user.getFirstName(), user.getLastName(),
                        user.getKmNumber()};
              if(user != null)
                m.addRow(data);
               _car = false;
               car = null;

            }
            if(tag.equalsIgnoreCase("employee") && _employeeSalary )
            {
            
             
             DefaultTableModel m = form.getEditEmployee().getModel();
            /* System.out.println(user.getFirstName()+ user.getLastName()+
                        user.getKmNumber());*/

             //System.out.println(employee.toString());
             Object [] data = {employee.getFirstName(), employee.getLastName(),
                        employee.getEarning(), employee.getWorkHours(),
                        employee.getBonus()};
              if(employee != null)
                m.addRow(data);
               _employee = false;
               employee = null;

            }

        }

        @Override
        public void endDocument() throws SAXException {
            super.endDocument();

            theEnd = true;

        }
    }

    public void list(String fname)  {
        try {
            XMLReader parser = XMLReaderFactory.createXMLReader();
            //("org.apache.crimson.parser.XMLReaderImpl");
            parser.setContentHandler(new ClientHandler());
            fileName = fname;
            parser.parse(fileName);

            while (theEnd == false);
             File file = new File(fileName);
            System.out.println("list file delete: "+file.delete());

                //Thread.sleep(5000);
            //File file = new File(fileName);
            //System.out.println("list file delete: "+file.delete());
       // } catch (InterruptedException ex) {
        //  Logger.getLogger(SaxParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SaxParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(SaxParser.class.getName()).log(Level.SEVERE, null, ex);
        }
       }


    public String getAnswer()
    {
        while(isAnswer == false)
            System.out.println("wait...");
        isAnswer = false;
        return answer;
    }
    public static void main(String[] args) throws Exception {
      // SaxParser p = new SaxParser();
       //p.list("S2C.xml");

       }
}


